package com.dhecp.project.storage.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.BidUtil;
import com.dhecp.core.utils.DateUtil;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.business.domain.ProductActive;
import com.dhecp.project.business.mapper.ProductActiveMapper;
import com.dhecp.project.common.domain.RecordCheck;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.hr.mapper.OperateCompanyApplyMapper;
import com.dhecp.project.storage.domain.StockControl;
import com.dhecp.project.storage.domain.StockControlRunning;
import com.dhecp.project.storage.domain.StockOpe;
import com.dhecp.project.storage.mapper.StockControlMapper;
import com.dhecp.project.storage.mapper.StockControlRunningMapper;
import com.dhecp.project.storage.mapper.StockOpeMapper;
import com.dhecp.project.storage.service.StockControlService;
import com.dhecp.project.storage.service.StockOpeService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * @program: kjecp
 * @description: 仓储 库存盘点单
 * @author: hlf
 * @create: 2022-09-01 16:09
 */
@Service
public class StockOpeServiceImpl extends BaseModuleServiceImpl implements StockOpeService {
	
	private String BID_PRE = "KCXG";

    @Autowired
    private StockOpeMapper stockOpeMapper;
    @Autowired
    private StockControlMapper stockControlMapper;
    @Autowired
    private StockControlRunningMapper stockControlRunningMapper;
    @Autowired
    private StockControlService stockControlService;
    @Autowired
    private ProductActiveMapper productActiveMapper;
    @Autowired
    private OperateCompanyApplyMapper operateCompanyApplyMapper;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;


    /**
     * @Description: 查询指定单nid的首记录
     * @Param: [params]
     * @return: com.dhecp.project.storage.domain.PurchaseAddress
     * @Author: hlf
     * @date: 2022-05-09 10:10
     */
    @Override
    public StockOpe findByGuid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");    //查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));    //数据权限查询条件SQL语句
        return stockOpeMapper.findById(params);
    }


    /**
     *@Description: 查询指定单nid的首记录
     *@Param: [params]
     *@return: com.dhecp.project.storage.domain.StockOpe
     *@Author: hlf
     *@date: 2022-05-09 10:10
     */
    @Override
    public StockOpe queryFirstRecord(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        return stockOpeMapper.selectFirstRecordByNid(params);
    }

    /**
     *@Description: 查询指定单nid的整单录
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: java.util.List<com.dhecp.project.storage.domain.StockOpe>
     *@Author: hlf
     *@date: 2022-05-09 10:10
     */
    @Override
    public List<StockOpe> queryListByNid(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        return stockOpeMapper.findStockOpe(params);
    }


    /**
     *@Description: 查询
     *@Param: [params]
     *@return: java.util.List<com.dhecp.project.storage.domain.StockOpe>
     *@Author: hlf
     *@date: 2022-05-09 10:10
     */
    @Override
    public List<StockOpe> queryList(Map<String, Object> params) throws Exception {
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        if (params.get("field") == null || params.get("field") == ""){
            String orderBy = "bid desc";
            PageUtils.startPageOrder(orderBy);
        }else{
            PageUtils.startPage();
        }
        return stockOpeMapper.select(params);
    }

    /**
     *@Description: 保存
     *@Param: [params] moduleTable 必要参数：功能唯一标识
     *@Param: [params] infoMap 必要参数：非网格字段（包括头部、底部所有显示和隐藏的字段）
     *@Param: [params] infoItems 必要参数：对应实体类的json格式字符串
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 10:10
     */
    @SuppressWarnings("unchecked")
    @Override
    public AjaxResult saveData(Map<String, Object> params) {
		params.put("businessEntity", new StockOpe());
		
		AjaxResult ajaxResult = this.saveDataBase(params);
		if (!"0".equals(ajaxResult.get("code").toString())){
			throw new RuntimeException(ajaxResult.get("msg").toString());
		}

		String resNid = "0";
		Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        List<StockOpe> businessDataList = (List<StockOpe>) ajaxResult.get("businessDataList");

    	List<RecordCheck> guidMapList = stockOpeMapper.findRecords(infoMap.get("nid").toString());
    	Map<String, Object> guidMap = new HashMap<String, Object>();
    	if (!guidMapList.isEmpty() && guidMapList.size() > 0){
    		if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())){ //单号重复验证
    			throw new RuntimeException(MessageUtils.message("module.error.retry"));
    		}
        	for (RecordCheck recordCheck : guidMapList){
        		if (recordCheck != null && recordCheck.getGuid() != null){
            		guidMap.put(recordCheck.getGuid().toString(), "1");
        		}
        	}
    	}
    	
		if (businessDataList == null || businessDataList.size() == 0){
			resNid = "0";
		}else{
			resNid = infoMap.get("nid").toString();
	        for (StockOpe businessData : businessDataList) {
	        	String guid = "";
	        	if (businessData.getGuid() == null){
	        		guid = RandomValueUtils.getGUID();
	        		businessData.setGuid(guid);
	        	}else{
	        		guid = businessData.getGuid().toString();
	        	}
	        	
	        	for (String field : infoMap.keySet()){ //遍历非网格字段，并赋值到实体中
	        		Object fieldValue = infoMap.get(field);
	        		ReflectUtils.setValue(businessData, field, fieldValue);
	        	}
	        	
	        	if (guidMap.get(guid) == null){
	        		stockOpeMapper.insert(businessData);
	        	}else{
	        		stockOpeMapper.update(businessData);
	        		guidMap.remove(guid);
	        	}
	        }
		}
			
    	if (!guidMap.isEmpty()){
    		for (String guid : guidMap.keySet()){
    			stockOpeMapper.delete(guid);
    		}
    	}
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"),resNid);
    }

    /**
     *@Description: 删除
     *@Param: [params]
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 10:11
     */
    @Override
    public AjaxResult deleteData(Map<String, Object> params) {
        List<StockOpe> businessDataList = JSON.parseArray(params.get("infoItems").toString(), StockOpe.class);
        if (businessDataList == null || businessDataList.size() == 0) {
            return AjaxResult.error(MessageUtils.message("module.error.jsontoentyerror"));
        }
        for (StockOpe businessData : businessDataList) {
            stockOpeMapper.delete(businessData);
        }
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"));
    }

	/**
	 * 新增库存修改
	 * @return
	 * @author EASE-xdh
	 */
	@Override
	public AjaxResult addStockOpeIn(String bid,
			String vGsBm,
			String vGsMc,
			String vGsJc,
			String productCode, Integer productNum,
			String locationHw,
			String locationKq,
			String locationArea,
			String remark
			) {
        
		if (productNum == null) {
			return AjaxResult.error("数量不能为空");
		} else if (productNum <= 0) {
			return AjaxResult.error("数量必须大于0");
		}

		// 入库验证
		if (productCode == null || productCode.length() == 0) {
			return AjaxResult.error("商品编码不能为空");
		}
		
		ProductActive productActive = productActiveMapper.findProductActiveByCode(productCode);
		if (productActive == null) {
			return AjaxResult.error("商品数据不存在");
		}

		if (vGsBm == null || vGsBm.length() == 0) {
			return AjaxResult.error("公司编码不能为空");
		}
		
		if (locationHw == null || locationHw.length() == 0) {
			return AjaxResult.error("货位编码不能为空");
		}
		
		if (stockOpeMapper.countByBid(bid) > 0) {
			return AjaxResult.error("该单号已存在，请刷新页面");
		}

		StockOpe entity = new StockOpe();
		entity.setBid(bid);
		entity.setProductNum(productNum);
		entity.setProductCode(productCode);
		entity.setProductName(productActive.getName());
		entity.setGuid(RandomValueUtils.getGUID());
		entity.setvGsBm(vGsBm);
		entity.setvGsMc(vGsMc);
		entity.setvGsJc(vGsJc);
		entity.setLocationHw(locationHw);
		entity.setLocationKq(locationKq);
		entity.setLocationArea(locationArea);
		entity.setCreateUser(ShiroUtils.getMandatorCid());
		entity.setRemark(remark);
		Date now = new Date();
		entity.setCreateTime(now);
		entity.setUpdateTime(now);
		stockOpeMapper.insert(entity);
		
		// 处理库存数据
		StockControl stockControl = new StockControl();
		{
			stockControl.setGuid(RandomValueUtils.getGUID());
			stockControl.setRkBid(entity.getBid());
			stockControl.setRkGuid(RandomValueUtils.getGUID());
			stockControl.setProductCode(entity.getProductCode());
			stockControl.setProductName(entity.getProductName());
			stockControl.setvHw(entity.getLocationHw());
			stockControl.setvKq(entity.getLocationKq());
			stockControl.setgDepot(entity.getLocationArea());
			stockControl.setvGsBm(entity.getvGsBm());
			stockControl.setvGsMc(entity.getvGsMc());
			stockControl.setvGsJc(entity.getvGsJc());
			stockControl.setProductNum(productNum);
			stockControl.setProductNumAll(productNum);
			stockControl.setdRkSj(now);
			stockControl.setCreateTime(now);
			stockControl.setIsParent(entity.getProductCode().contains("-") ? "0" : "1");
			stockControlMapper.insert(stockControl);
		}
		
		// 添加库存流水
		StockControlRunning stockControlRunning = new StockControlRunning();
		stockControlRunning.setGuid(RandomValueUtils.getGUID());
		stockControlRunning.setGuidStockControl(stockControl.getGuid());
		stockControlRunning.setBidRelative(bid);
		stockControlRunning.setLocationHw(stockControl.getvHw());
		stockControlRunning.setProductCode(stockControl.getProductCode());
		stockControlRunning.setvGsBm(stockControl.getvGsBm());
		stockControlRunning.setProductNumChange(productNum);
		stockControlRunning.setProductNumLeft(stockControl.getProductNum());
		stockControlRunning.setCreateTime(now);
		
		
		stockControlRunning.setRemark("入库修改单" + bid);
		stockControlRunningMapper.insert(stockControlRunning);
		return AjaxResult.success("操作成功");
	}


	@Override
	public AjaxResult addStockOpeOut(String bid, String guidStockControl, Integer productNum, String remark) {
		
		if (stockOpeMapper.countByBid(bid) > 0) {
			return AjaxResult.error("该单号已存在，请刷新页面");
		}
		
		// 出库验证
		StockControl stockControl = stockControlService.findByGuid(guidStockControl);
		if (stockControl == null) {
			return AjaxResult.error("库存数据不存在");
		} else if (productNum >= 0) {
			return AjaxResult.error("出库数量必须小于0");
		} else if (stockControl.getProductNum() + productNum < 0) {
			return AjaxResult.error("出库数量不能高于库存数量");
		}
		
		// 添加库存修改单
		StockOpe entity = new StockOpe();
		entity.setBid(bid);
		entity.setGuid(RandomValueUtils.getGUID());
		entity.setCreateUser(ShiroUtils.getMandatorCid());
		entity.setRemark(remark);
		Date now = new Date();
		entity.setCreateTime(now);
		entity.setUpdateTime(now);
		entity.setvGsMc(stockControl.getvGsMc());
		entity.setvGsJc(stockControl.getvGsJc());
		entity.setvGsBm(stockControl.getvGsBm());
		entity.setProductName(stockControl.getProductName());
		entity.setProductCode(stockControl.getProductCode());
		entity.setProductNum(productNum);
		entity.setLocationHw(stockControl.getvHw());
		entity.setLocationKq(stockControl.getvKq());
		entity.setLocationArea(stockControl.getgDepot());
		stockOpeMapper.insert(entity);
		
		{
			stockControl.setProductNum(stockControl.getProductNum() + productNum);
			stockControl.setProductNumAll(stockControl.getProductNumAll() + productNum);
			stockControlMapper.update(stockControl);
		}
		
		// 添加库存流水
		StockControlRunning stockControlRunning = new StockControlRunning();
		stockControlRunning.setGuid(RandomValueUtils.getGUID());
		stockControlRunning.setGuidStockControl(stockControl.getGuid());
		stockControlRunning.setBidRelative(bid);
		stockControlRunning.setLocationHw(stockControl.getvHw());
		stockControlRunning.setProductCode(stockControl.getProductCode());
		stockControlRunning.setvGsBm(stockControl.getvGsBm());
		stockControlRunning.setProductNumChange(productNum);
		stockControlRunning.setProductNumLeft(stockControl.getProductNum());
		stockControlRunning.setCreateTime(now);
		
		
		stockControlRunning.setRemark("入库修改单" + bid);
		stockControlRunningMapper.insert(stockControlRunning);
		return AjaxResult.success("");
	}


	@Override
	public String getBidForAdd() {
		String yyMMdd = DateUtil.getYYYY_MM_DD(new Date()).replace("-", "").substring(2);
		
		String bid = stockOpeMapper.getLatestBid();
		if (bid == null) {
			return BID_PRE + "-" + yyMMdd + "-1001";
		} else {
			if (bid.startsWith(BID_PRE + "-" + yyMMdd)) {
				Integer bidLast = Integer.parseInt(bid.substring(bid.lastIndexOf("-") + 1)) + 1;
				return BID_PRE + "-" + yyMMdd + "-" + BidUtil.parseIntToFourLen(bidLast);
			} else {
				return BID_PRE + "-" + yyMMdd + "-1001";
			}
		}
	}
}